import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import { Table, Tag, Tooltip } from 'antd';
import DetectResult from '@components/detect-result';
import WebResult from '@components/web-result';
import _ from 'lodash';
import { connect } from 'react-redux';
import { transDeviceName } from '@util/trans-device-name';
import './index.less';

const ResultTable = props => {
  const { data, onChange, filter = {}, total = 0, scanType = 'Zoomeye', modules = [] } = props;
  let updatedElement = <span className="updated">[有更新]</span>;
  let isNewElement = <span className="is-new">[新增]</span>;
  let columns = [],
    onRowExpan;
  if (scanType === 'Zoomeye') {
    columns = [
      {
        title: 'IP',
        width: 200,
        dataIndex: 'ip',
        render: (ip, row) => {
          return (
            <div>
              {ip}
              {_.get(row, 'is_new_ip') && isNewElement}
              {_.get(row, 'detection_updated') && updatedElement}
            </div>
          );
        }
      },
      {
        title: '存活端口数',
        width: 120,
        dataIndex: 'servicePortComponent.length'
      },
      {
        title: '存活端口',
        dataIndex: 'servicePortComponent',
        className: 'ports-wrapper',
        render: (servicePortComponent = []) => {
          const ports = servicePortComponent.map(i => i.port).filter(Boolean);
          let showProts = ports,
            lastPort = null;
          if (ports.length > 10) {
            showProts = ports.slice(0, 9);
            lastPort = (
              <Tooltip title={ports.join(',')}>
                <Tag className="port">...</Tag>
              </Tooltip>
            );
          }
          const ele = (
            <div>
              {showProts.map(port => (
                <Tag key={port} className="port">
                  {port}
                </Tag>
              ))}
              {lastPort}
            </div>
          );
          return ele;
        }
      },
      {
        title: 'Ping',
        dataIndex: 'pingable',
        className: 'ping-wrapper',
        render: i => {
          return i ? <span>有响应</span> : <span>无响应</span>;
        }
      }
    ];
    if (_.includes(modules, 'ip-location')) {
      columns.push({
        title: '地理位置',
        key: 'location',
        className: 'location',
        render: (i = {}) => {
          return i.country === '局域网'
            ? i.country
            : [i.country, i.region, i.city].filter(Boolean).join('-') || '-';
        }
      });
    }
    onRowExpan = row => {
      const os = _.get(row, 'oss[0]');
      const device = transDeviceName(_.union(_.get(row, 'devices', []))).join(',');
      const ele = (
        <DetectResult
          os={os}
          device={device}
          items={_.get(row, 'servicePortComponent', [])}
          row={row}
        />
      );
      return ele;
    };
  } else if (scanType === 'Web') {
    columns = [
      {
        title: '资产',
        dataIndex: 'site_oid',
        render: (site = {}, row) => (
          <div>
            {`${_.get(site, 'ip') || '-'}(${_.get(site, 'url') || '-'})`}
            {_.get(row, 'is_new_ip') && isNewElement}
          </div>
        ),
        className: 'web-ip'
      },
      {
        title: 'Web应用',
        dataIndex: 'web_apps',
        render: (data = []) => data.join(', ').trim() || '-',
        width: '10%'
      },
      {
        title: 'Web容器',
        dataIndex: 'web_servers',
        render: (data = []) => data.join(', ').trim() || '-',
        width: '10%'
      },
      {
        title: 'Web框架',
        dataIndex: 'web_framworks',
        render: (data = []) => data.join(', ').trim() || '-',
        width: '10%'
      },
      {
        title: '防护信息',
        dataIndex: 'web_wafs',
        render: (data = []) => data.join(', ').trim() || '-',
        width: '10%'
      },
      {
        title: '数据库',
        dataIndex: 'web_dbs',
        render: (data = []) => data.join(', ').trim() || '-',
        width: '10%'
      },
      {
        title: '开发语言',
        dataIndex: 'web_languages',
        render: (data = []) => data.join(', ').trim() || '-',
        width: '10%'
      }
    ];
    onRowExpan = row => {
      const ele = <WebResult data={row} />;
      return ele;
    };
  }

  const pagination = {
    current: filter.page || 1,
    pageSize: filter.pageSize || 10,
    total: total,
    showQuickJumper: true,
    showSizeChanger: true,
    showTotal: num => `共 ${num} 条`,
    size: 'small'
  };

  const [expandedRowKeys, setExpandedRowKeys] = useState([]);

  const onTableChange = ({ current, pageSize }) => {
    onChange(current, pageSize);
  };

  useEffect(() => {
    setExpandedRowKeys([]);
  }, [data]);

  return (
    <div className="tmd-c-result-table">
      <Table
        rowKey={'ip'}
        columns={columns}
        pagination={pagination}
        loading={false}
        onChange={onTableChange}
        dataSource={data}
        expandedRowKeys={expandedRowKeys}
        expandRowByClick={true}
        onExpandedRowsChange={setExpandedRowKeys}
        expandedRowRender={onRowExpan}
        rowClassName={record => {
          if (expandedRowKeys.indexOf(record.ip) !== -1) {
            return 'expaned';
          }
        }}
      />
    </div>
  );
};

ResultTable.propTypes = {
  data: PropTypes.array,
  filter: PropTypes.object,
  total: PropTypes.number,
  onChange: PropTypes.func,
  scanType: PropTypes.string,
  modules: PropTypes.arrayOf(PropTypes.string)
};

const mapStateToProps = state => {
  return {
    modules: _.get(state, 'auth.cert.modules', [])
  };
};

export default connect(
  mapStateToProps,
  null
)(ResultTable);
